package com.lbd.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lbd.common.utils.R;
import com.lbd.gulimall.cart.constrant.CartConstrant;
import com.lbd.gulimall.cart.feign.ProductFeignService;
import com.lbd.gulimall.cart.interceptor.CartInterceptor;
import com.lbd.gulimall.cart.service.CartService;
import com.lbd.gulimall.cart.to.OnlineUserTO;
import com.lbd.gulimall.cart.vo.CartItemVO;
import com.lbd.gulimall.cart.vo.CartVO;
import com.lbd.gulimall.cart.vo.SkuInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @Author: linbd
 * @Description:
 * @Date: 2023/3/25 14:25
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private ThreadPoolExecutor executor;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ProductFeignService productFeignService;

    //添加购物车，如果商品存在则更新数量
    @Override
    public CartItemVO addToCart(Long skuId, Integer count) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> op = getHashOperation();
        String item = (String) op.get(skuId.toString());
        //当前商品已经在购物车中，则更新商品数量；不在购物车中，就向购物车添加一个新的
        if (!StringUtils.isEmpty(item)) {
            CartItemVO cartItem = JSON.parseObject(item, CartItemVO.class);
            cartItem.setCount(cartItem.getCount() + count);
            log.info("购物车商品已存在，更新数量... 新的商品信息 【{}】", cartItem);
            op.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        } else {
            CartItemVO cartItemVO = new CartItemVO();
            //查询sku商品信息
            CompletableFuture<Void> skuInfoFuture = CompletableFuture.runAsync(() -> {
                R r = productFeignService.info(skuId);
                if (r.getCode() == 0) {
                    SkuInfoVO skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVO>() {
                    });
                    cartItemVO.setSkuId(skuId);
                    cartItemVO.setChecked(true);
                    cartItemVO.setImage(skuInfo.getSkuDefaultImg());
                    cartItemVO.setTitle(skuInfo.getSkuTitle());
                    cartItemVO.setCount(count);
                    cartItemVO.setPrice(skuInfo.getPrice());
                }
            }, executor);
            //查询sku商品销售属性
            CompletableFuture<Void> skuSaleAttrFuture = CompletableFuture.runAsync(() -> {
                R r = productFeignService.getSaleAttrBySkuId(skuId);
                if (r.getCode() == 0) {
                    List<String> saleAttrs = r.getData(new TypeReference<List<String>>() {
                    });
                    cartItemVO.setSkuSaleList(saleAttrs);
                }
            }, executor);
            CompletableFuture.allOf(skuInfoFuture, skuSaleAttrFuture).get();
            log.info("新增购物车商品... 新的商品信息 【{}】", cartItemVO);
            op.put(skuId.toString(), JSON.toJSONString(cartItemVO));
            return cartItemVO;
        }
    }

    //获取当前用户下，某个skuId对应的购物车商品
    @Override
    public CartItemVO getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> op = getHashOperation();
        String res = (String) op.get(skuId.toString());
        CartItemVO cartItemVO = JSON.parseObject(res, CartItemVO.class);
        return cartItemVO;
    }

    //删除整个购物车
    @Override
    public void delCart(String key) {
        stringRedisTemplate.delete(key);
    }

    //根据skuId修改购物车某件商品的选中状态
    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> op = getHashOperation();
        String s = (String) op.get(skuId.toString());
        CartItemVO item = JSON.parseObject(s, CartItemVO.class);
        item.setChecked(check == 1);
        op.put(skuId.toString(),JSON.toJSONString(item));
    }

    //根据skuId修改购物车某件商品的数量
    @Override
    public void checkCount(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> op = getHashOperation();
        String s = (String) op.get(skuId.toString());
        CartItemVO item = JSON.parseObject(s, CartItemVO.class);
        item.setCount(num);
        op.put(skuId.toString(),JSON.toJSONString(item));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> op = getHashOperation();
        op.delete(skuId.toString());
    }

    @Override
    public List<CartItemVO> getAllSelectedCartItem() {
        OnlineUserTO user = CartInterceptor.onlineUser.get();
        if (!StringUtils.isEmpty(user.getUserId())) {
            BoundHashOperations<String, Object, Object> op = stringRedisTemplate.boundHashOps(CartConstrant.CART_USER_PREFIX + user.getUserId());
            List<Object> values = op.values();
            if (values != null && values.size() > 0) {
                List<CartItemVO> cartItems= values.stream()
                        .map(value -> JSON.parseObject((String) value, CartItemVO.class))
                        .filter(CartItemVO::getChecked)
                        .map(item -> {
                            //重设购物车中的商品价格，保证是最新价格
                            R r = productFeignService.getPrice(item.getSkuId());
                            if (r.getCode() == 0) {
                                BigDecimal price = r.getData(new TypeReference<BigDecimal>() {
                                });
                                item.setPrice(price);
                            }
                            return item;
                        })
                        .collect(Collectors.toList());
                return cartItems;
            }
        }
        return null;
    }

    //获取和合并购物车
    @Override
    public CartVO getCart() throws ExecutionException, InterruptedException {
        OnlineUserTO user = CartInterceptor.onlineUser.get();
        CartVO cartVO = new CartVO();
        if (!StringUtils.isEmpty(user.getUserId())) {
            //已经登录
            //获取临时购物车，合并临时购物车 到 登陆用户购物车中
            List<CartItemVO> tempCartItems = getCartItemByCartKey(CartConstrant.CART_USER_PREFIX + user.getUserKey());
            if (tempCartItems != null && tempCartItems.size() > 0) {
                for (CartItemVO tempCartItem : tempCartItems) {
                    //向当前用户购物车中添加商品
                    addToCart(tempCartItem.getSkuId(),tempCartItem.getCount());
                }
                //合并后清空临时购物车
                delCart(CartConstrant.CART_USER_PREFIX + user.getUserKey());
            }
            //获取登录用户的购物车
            List<CartItemVO> cartItems = getCartItemByCartKey(CartConstrant.CART_USER_PREFIX + user.getUserId());
            cartVO.setCartItems(cartItems);
        } else {
            //获取临时用户购物车
            List<CartItemVO> cartItems = getCartItemByCartKey(CartConstrant.CART_USER_PREFIX + user.getUserKey());
            cartVO.setCartItems(cartItems);
        }
        return cartVO;
    }

    //根据键名 （userId/userKey），获取购物车所有的商品列表
    private List<CartItemVO> getCartItemByCartKey(String key) {
        BoundHashOperations<String, Object, Object> op = stringRedisTemplate.boundHashOps(key);
        List<Object> values = op.values();
        if (values != null && values.size() > 0) {
            List<CartItemVO> cartItems= values.stream()
                    .map(value -> JSON.parseObject((String) value, CartItemVO.class)).collect(Collectors.toList());
            return cartItems;
        }
        return null;
    }

    //根据线程中的用户信息获取对应hash操作对象
    private BoundHashOperations<String, Object, Object> getHashOperation() {
        OnlineUserTO user = CartInterceptor.onlineUser.get();
        String key = "";
        if (!StringUtils.isEmpty(user.getUserId())) {
            //已登录的用户
            key = CartConstrant.CART_USER_PREFIX + user.getUserId();
        } else {
            //未登录的临时用户
            key = CartConstrant.CART_USER_PREFIX + user.getUserKey();
        }
        //为操作对象绑定hash键
        BoundHashOperations<String, Object, Object> op = stringRedisTemplate.boundHashOps(key);
        return op;
    }


}
